// pages/ticket/car_ticket.js

var app = getApp();
var util= require('../../utils/util.js')

var _moment = require("../../lib/moment.js");

var moment = require("../../utils/moment.js");

var _moment2 = _interopRequireDefault(_moment);
var _fun = require("../../lib/fun.js");
var _modal = require("../../lib/modal.js");

var _modal2 = _interopRequireDefault(_modal);

var _extends = Object.assign || function(target) {
  for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];
      for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
          }
      }
  }
  return target;
};


function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}

var modal = _extends(function(){}, _fun.modal);
import Dialog from '../../vant/dialog/dialog';
Page({

    /**
     * 页面的初始数据
     */
    data: {
      parameter: {
        'navbar': '1',
        'return': '1',
        'title': '拼团列表',
        'color': false,
      },
        regularDate:'',
        busLineId:'',
        defautltRegular:[],
        calendar:[],
        curMonth: (0, _moment2.default)().format("YYYY年MM月"),
        regularList:[],
        defaultRegularId:'',
        regularId:'',
        peopleNum: 1,
        coupon: { coupon: false, list: [], statusTile:'立即使用'},//优惠券组件
        openType:1,//优惠券打开方式 1=使用
        couponTitle:'请选择',//优惠券
        coupon_price:0,//优惠券抵扣金额
        couponId:0,//优惠券id
        userInfo:{},//用户信息
        mark:'',//备注信息
        useIntegral:false,//是否使用积分
        integral_price:0,//积分抵扣金额
        ChangePrice:0,//使用积分抵扣变动后的金额
        upArr: [], // 上车点数组
        downArr:[], // 下车点数组
        selectRegular: [],
        upPoint: {},
        downPoint: {},
        active:0,//支付方式切换
         //支付方式
        cartArr: [
          { "name": "微信支付", "icon": "icon-weixin2", value: 'weixin', title: '微信快捷支付' },
          { "name": "余额支付", "icon": "icon-icon-test", value: 'yue',title:'可用余额:'},
        ],
        payType:'weixin',//支付方式
        showRight: false,
        toPay:false,//修复进入支付时页面隐藏从新刷新页面
        isLogin: true,
        isBifa: false
    },
  
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({ 
            busLineId: options.lineId,
            lineOrigin: options.lineOrigin,
            lineDestination: options.lineDestination,
            lineSn: options.lineSn
          });
          this.getDefaultRegular(options.lineId);

          this.myModal = new _modal2.default(this);
    },
      /**
   * 授权回调
  */
  onLoadFun:function(){
    this.getCouponList();
    
    if(!app.globalData.userPhone){
      this.setData({
        isLogin: false
      })

      }else{
        this.setData({
          isLogin: true
        })
      }

      // this.getConfirm();
    // this.getUserInfo();
    // if (!this.data.MyMenus.length) this.getMyMenus();
  },
   /**
   * 获取当前金额可用优惠券
   * 
  */
 getCouponList:function(){
    var that=this;
    app.baseGet(app.U({ c: "coupons_api", a: 'get_use_coupon_order', q: { totalPrice:this.data.totalPrice }}),function(res){
      that.setData({ 'coupon.list': res.data, openType:1});
    });
  },
  getDefaultRegular:function(id){
    var that = this;
    var url = app.U({ c: 'public_api', a: 'get_default_regular' ,q:{id:id}}, app.globalData.url);
    app.baseGet(url,function(res){  
      if(res.data.length){
      res.data[0].checked = true; 
      that.setData({
        regular: res.data[0]
      })
      that.getRegularDate(id, res.data[0]['date']);
    }
    });
  },
  
  getRegularDate:function(busLineId,regularDate){
        var _this1 = this;
        var url = app.U({ c: 'public_api', a: 'get_regular_date' ,q:{bus_line_id:busLineId,regular_date:regularDate}}, app.globalData.url);
        app.baseGet(url,function(res){  
            var data = res.data
            var rili = _this1.formatCalendar(data[0]);
            _this1.setData({
                calendar: rili,
                defautltRegular: data[1],
            })
            // if(data[1]['seat']){ // 如果上一页面选择的班次卖完了 就要重新选择
            //     this.setData({
            //         regularList: [],
            //     })
            // } else{
            //     _this1.setData({
            //         regularList: data[1]
            //     })
            // }
            _this1.defaultSelected();
        });
      },

    getBusStop:function(id=this.data.busLineId){
      var that = this;
      that.setData({
        upArr: [],
        downArr: [],
    });
      var updian = [];
      var downdian = [];
      var url = app.U({ c: 'public_api', a: 'get_bus_stop' ,q:{id:id}}, app.globalData.url);
      app.baseGet(url,function(res){  
        var busStop = res.data[0]
        for (var i = 0 ;i<busStop.length;i++) {
          if (busStop[i]['type'] == 0) {
            updian.push({
                  // text: busStop[i]['name'] + '(' + that.getSj(busStop[i]['hastime']) + ')',
                  id: busStop[i]['id'],
                  name: busStop[i]['name'],
                  // time: that.getSj(busStop[i]['hastime'])
              })
          }else {
            downdian.push({
                  // text: busStop[i]['name'] + '(' + that.getSj(busStop[i]['hastime']) + ')',
                  id: busStop[i]['id'],
                  name: busStop[i]['name'],
                  // time: that.getSj(busStop[i]['hastime'])
              })
          }
      }
        that.setData({
          upArr: updian,
          downArr: downdian,
          upPoint: updian[0],
          downPoint: downdian[(downdian.length-1)],
        })

      });
    },  
    getSj:function(value) {
      let _this = this
      let date = _this.data.selectRegular.date
      let startTime = _this.data.selectRegular.starttime

      let timeT = moment(moment.unix(date).format('YYYY-MM-DD')  + ' ' + startTime).unix()
      let timeF = timeT + (value * 60)
      return moment(timeF * 1000).format('HH:mm')
    },
     //选择上车站
     startStationPickerChange: function startStationPickerChange(e) {
      var _this16 = this;
      var index = e.detail.value;
      this.setData({
          upPoint: _this16.data.upArr[index],
      });
  },
  // 选择下车站
  endStationPickerChange: function endStationPickerChange(e) {
      var _this16 = this;
      var index = e.detail.value;
      this.setData({
          downPoint: _this16.data.downArr[index],
      });
  },

    formatCalendar:function(calendarList) {
          var _this2 = this;
        var calendar = calendarList.map(function(item) {
            item.dateShort = item.date.split("-")[2];
            item.inventoryStatus = _this2.inventoryInfo(item.stock);
            return item;
        });

        return calendar;
        // var firstDate = calendarList[0];
        // if (!firstDate) {
        //     return calendar;
        // }
        // var firstDateDay = (0, _moment2.default)(firstDate.date, "YYYY-MM-DD").day();
        // for (var i = 0; i < firstDateDay; i++) {
        //     calendar.unshift({});
        // }
        // return calendar;
    },
    inventoryInfo:function(inventory) {
        var inventoryStatus = "";
        if (inventory < 0) {
            inventoryStatus = "";
        } else if (inventory == 0) {
            inventoryStatus = "售罄";
        } else {
            inventoryStatus = "在售";
        }
        return inventoryStatus;
    },
    onDaySelect: function onDaySelect(e) {
        var _this14 = this;
        for (var i = 0, len = _this14.data.regularList.length; i < len; i++) {
          if(_this14.data.regularList[i].isSelected ==true) _this14.data.regularList[i].isSelected  = false;
      }
        var tapIndex = e.currentTarget.dataset.index;
        var calendar = this.data.calendar;
        var tapDate = calendar[tapIndex];
        for (var i = 0, len = calendar.length; i < len; i++) {
            if(calendar[i].checked ==true) calendar[i].checked = false;
        }
        if (tapDate.stock > 0) {
            tapDate.checked = !tapDate.checked;
            calendar[tapIndex].regular[0]['isSelected'] = true

            _this14.setData({
                regularList: calendar[tapIndex].regular,
                regularId: calendar[tapIndex].regular[0]['id'],
                selectRegular: calendar[tapIndex].regular[0],
                isBifa: calendar[tapIndex].regular[0]['bifa'],
                totalPrice: calendar[tapIndex].regular[0]['price']*_this14.data.peopleNum-_this14.data.coupon_price-_this14.data.integral_price
            });
        }
        _this14.setData({
            calendar: this.data.calendar,
        }, function() {
            var calender = _this14.data.calendar;
            var firstSelectedDate = calender.find(function(item) {
                return item.checked;
            });
            if (firstSelectedDate && firstSelectedDate.date) {
                _this14.setData({
                    selectedMonth: (0, _moment2.default)(firstSelectedDate.date, "YYYY-MM-DD").format("YYYY年MM月")
                });
            } else {
                _this14.setData({
                    selectedMonth: false
                });
            }
            // actions.computePrice.call(_this14, true);
        });
        console.log(_this14.data.regularList)
        _this14.getBusStop();
    },
    changeLinePlan: function changeLinePlan(e) {
        var _this13 = this;
        var target = e.currentTarget;
        var index = target.dataset.opidx;
        var reList = _this13.data.regularList
        
        reList.forEach(function(item, i) {
            if (item.id === index) {
                item.isSelected = true;
                _this13.setData({
                    regularId: item.id,
                    selectRegular: item,
                    isBifa: item.bifa,
                    totalPrice: item['price']*_this13.data.peopleNum-_this13.data.coupon_price-_this13.data.integral_price
                })
            } else {
                item.isSelected = false;
            }
        });
        _this13.setData({
            regularList: reList,
        })
        _this13.getBusStop()


    },
    defaultSelected: function defaultSelected() {
        var _this6 = this;
        var calendar = this.data.calendar;
    
        var selectedMonth = false;
        for (var i = 0, len = calendar.length; i < len; i++) {
    
          var defaultDate = (0, _moment2.default)(_this6.data.defautltRegular[0]['date']*1000).format('YYYY-MM-DD')
            if(_this6.data.defautltRegular[0]['seat']!=0){
                if(defaultDate==calendar[i].date){
                    calendar[i].checked = true;
                    selectedMonth = (0, _moment2.default)(calendar[i].date, "YYYY-MM-DD").format("YYYY年MM月");
                    _this6.setData({
                        regularList: calendar[i].regular,
                        regularId: _this6.data.defaultRegularId,
                    })
                    break;
                }

            } else{
            if (calendar[i].stock > 0) {
                calendar[i].checked = true;
                selectedMonth = (0, _moment2.default)(calendar[i].date, "YYYY-MM-DD").format("YYYY年MM月");
                _this6.setData({
                    regularList: calendar[i].regular,
                    regularId: calendar[i].regular[0]['id']
                })
                break;
        }
    }

    
    }
        var reList = _this6.data.regularList;
     
        reList.forEach(function(item, i) {
            if (item.id == _this6.data.regularId) {
                item.isSelected = true;
                _this6.setData({
                  selectRegular: item,
                  isBifa: item.bifa,
                  totalPrice: item['price']*_this6.data.peopleNum-_this6.data.coupon_price-_this6.data.integral_price
                  
              })
            } else {
                item.isSelected = false;
            }
        });

        _this6.setData({
            calendar: calendar,
            selectedMonth: selectedMonth,
            regularList: reList,
        }, function() {
            //获取优惠券列表
            // apis.getCouponList.call(_this6, {
            //     lineId: _this6.data.lineId
            // });
            // actions.computePrice.call(_this6);
        });
        console.log( _this6.data.regularList)
        _this6.getBusStop()

    },
    onChange:function(e){
      
        this.setData({
            peopleNum: e.detail,
            totalPrice: this.data.selectRegular['price']*e.detail-this.data.coupon_price-this.data.integral_price
        })
      },
    coupon: function () {
        this.setData({
          'coupon.coupon': true
        })
      },
      ChangCouponsClone:function(){
        this.setData({'coupon.coupon':false});
      },
        /**
   * 处理点击优惠券后的事件
   * 
  */
  ChangCoupons:function(e){
    var index = e.detail, list = this.data.coupon.list, couponTitle = '请选择', couponId = 0, coupon_price = 0, totalPrice = 0, 
        change_coupon_price=0;
    for (var i = 0, len = list.length; i < len; i++) {
      if(i != index){
        list[i].use_title = '';
        list[i].is_use = 0;
      }
      //获取当前优惠券抵扣金额
      if (list[i].id == this.data.couponId) change_coupon_price = list[i].coupon_price;
    }
    if (this.data.totalPrice <= 0 && this.data.status != 1) return app.Tips({title:'支付金额为0无法使用优惠卷！'});
    if (this.data.status==1 || this.data.is_address) {
      this.setData({ totalPrice: this.data.priceGroup.totalPrice });
    }else{
      //使用优惠券抵扣前先把之前的抵扣金额加回去
      this.setData({ totalPrice: util.$h.Add(this.data.totalPrice, change_coupon_price) });
    }
    if (list[index].is_use) {
      //不使用优惠券
      list[index].use_title = '';
      list[index].is_use = 0;
      totalPrice = this.data.totalPrice;
      //用户取消使用优惠卷但是使用了积分抵扣
      if (totalPrice > 0 && this.data.useIntegral) totalPrice = this.changeCouponPrice(totalPrice, this.data.userInfo.integral);
      this.data.status = 0;
    } else {
      //使用优惠券
      list[index].use_title = '不使用';
      list[index].is_use = 1;
      couponTitle = list[index].coupon_title;
      couponId = list[index].id;
      coupon_price = list[index].coupon_price;
     //使用积分抵扣,使用优惠券金额大于当前支付金额
      if (this.data.totalPrice < coupon_price && this.data.useIntegral){
        //超出金额
        var changePrice = util.$h.Sub(coupon_price, this.data.totalPrice);
        //超出回退积分
        var changeIntegral = util.$h.Div(changePrice, this.data.integralRatio);
        //回退积分和积分抵扣金额
        this.setData({ 
          integral: util.$h.Add(this.data.integral, changeIntegral), 
          integral_price: util.$h.Sub(this.data.integral_price, changePrice)
        });
        totalPrice=0;
        this.data.status=0;
      } else if (this.data.totalPrice < coupon_price && !this.data.useIntegral){
        //使用优惠券金额大于当前支付金额
        totalPrice=0;
        this.data.status=1;
      } else if (this.data.totalPrice > coupon_price && this.data.useIntegral){
        //支付金额大于优惠券金额并且使用了积分
        totalPrice = util.$h.Sub(this.data.totalPrice, list[index].coupon_price);
        //当前优惠券大于0的时候再去减去可兑换的金额
        if (this.data.integral > 0) totalPrice = this.changeCouponPrice(totalPrice, this.data.integral);
        this.data.status = 0;
      } else if (this.data.totalPrice > coupon_price && !this.data.useIntegral){
        //支付金额大于优惠券金额没有使用积分
        totalPrice = util.$h.Sub(this.data.totalPrice, list[index].coupon_price);
        this.data.status = 0;
      }
    }
    this.setData({ 
      couponTitle: couponTitle, 
      couponId: couponId, 
      'coupon.coupon': false, 
      "coupon.list":list,
      coupon_price: coupon_price,
      totalPrice: totalPrice,
      status: this.data.status,
    });
  },
   /**
   * 处理点击优惠券后支付金额和积分变动
   * @param string | float totalPrice 当前支付金额
   * @return float totalPrice 当前支付金额
   * 
  */
  changeCouponPrice: function (totalPrice, integral){
    var changePrice = util.$h.Mul(this.data.integralRatio,integral);
    this.data.integral_price=0;
    if (changePrice > totalPrice) {
      //超出金额
      var minParice = util.$h.Sub(changePrice, totalPrice);
      //超出积分
      var changeIntegral = util.$h.Div(minParice, this.data.integralRatio);
      //抵扣金额需要原本的订单金额
      this.setData({ integral: changeIntegral, integral_price: this.data.totalPrice });
      //超出金额当前支付金额为0
      totalPrice=0;
    } else {
      this.setData({ integral: 0, integral_price: util.$h.Add(this.data.integral_price, changePrice) });
      totalPrice = util.$h.Sub(totalPrice, changePrice);
    }
    return totalPrice;
  },
  /**
   * 使用积分抵扣
  */
  ChangeIntegral:function(){
    var integral=parseFloat(this.data.integral);
    if (this.data.userInfo.integral <= 0) return app.Tips({ title: '您当前积分为较低不能使用抵扣' }, function () { 
      this.setData({ useIntegral:false });
    }.bind(this));
    if (this.data.totalPrice <= 0 && !this.data.useIntegral) return app.Tips({title:'当前支付金额不能在使用积分抵扣啦~'},function(){
      this.setData({ useIntegral: false });
    }.bind(this));
    this.setData({useIntegral:!this.data.useIntegral});
    //使用积分抵扣时
    if (this.data.useIntegral){
      var changePrice = util.$h.Mul(this.data.integralRatio, integral);
      if (changePrice > this.data.totalPrice){
        //超出金额
        var minParice = util.$h.Sub(changePrice, this.data.totalPrice);
        //超出积分
        var changeIntegral = util.$h.Div(minParice, this.data.integralRatio);
        //超出当前金额支付金额为0,积分抵扣金额为当前支付金额,积分剩余等于超出积分
        this.setData({ integral: changeIntegral, integral_price:this.data.totalPrice,totalPrice:0});
      }else{
        this.setData({ integral: 0, integral_price: changePrice, totalPrice: util.$h.Sub(this.data.totalPrice, changePrice)});
      }
    }else{
      var integral_price = this.data.integral_price;
      //不使用积分返回原始数据
      this.setData({ integral_price: 0, integral: this.data.userInfo.integral, totalPrice: util.$h.Add(this.data.totalPrice, integral_price.toString())});
    }
  },
  payItem:function(e){
    var that = this;
    var active = e.currentTarget.dataset.index;
    that.setData({
      active: active,
      animated: true,
      payType: that.data.cartArr[active].value,
    })
    setTimeout(function () {
      that.car();
    }, 500);
  },
  car: function () {
    var that = this;
    that.setData({
      animated: false
    });
  },
  openNotice:function(){
    var that = this;
    that.setData({
      showRight: true
    });
  },
  closeNotice:function(){
    var that = this;
    that.setData({
      showRight: false
    });
  },

 /**
   * 获取当前订单详细信息
   * 
  */
//  getConfirm:function(){
//   var that=this;
//   app.basePost(app.U({ c: 'auth_api', a: 'confirm_order' }), {},function(res){
//     that.setData({
//       userInfo: res.data.userInfo,
//       integral: res.data.userInfo.integral,
//       integralRatio: res.data.integralRatio,
//       offlinePostage: res.data.offlinePostage,
//     });
//     that.data.cartArr[1].title ='可用余额:'+ res.data.userInfo.now_money;
//     that.setData({ cartArr: that.data.cartArr, ChangePrice:that.data.totalPrice});

//   },function(res){
//     return app.Tips({title:res.msg},{tab:3,url:1});
//   });
// },

  SubOrder:function(e){
    var that = this
    if(!app.globalData.userPhone){
      
    // Dialog.confirm({
    //   title: '登录提示',
    //   message: '您未绑定手机号，请先绑定！'
    // }).then(() => {
    //   wx.navigateTo({
    //     url: "/pages/login/login"
    // })
    // }).catch(() => {
    //   // on cancel
    // });

    that.setData({isLogin: false})
    } else{
      if (!that.data.payType) return app.Tips({title:'请选择支付方式'});
      if (!that.data.regularId) return app.Tips({title:'请选择班次'});
       var data={
        // formId: formId,
        // couponId: that.data.couponId,
        // payType: that.data.payType,
        // useIntegral: that.data.useIntegral,
        // bargainId: that.data.BargainId,
        // combinationId: that.data.combinationId,
        // pinkId: that.data.pinkId,
        // seckill_id: that.data.seckillId,
        // mark: that.data.mark
        cartNum: that.data.peopleNum,
         regularId: that.data.selectRegular.id
      };
      if (that.data.payType == 'yue' && parseFloat(that.data.userInfo.now_money) < parseFloat(that.data.totalPrice)) return app.Tips({title:'余额不足！'});
      wx.showLoading({ title: '订单支付中'});
      app.basePost(app.U({ c: 'auth_api', a:'now_bus_buy'}),data,function(res){
        var pdata = {
          formId: e.detail.formId,
          couponId:that.data.couponId,
          mark:that.data.mark,
          payType:that.data.payType,
          useIntegral:that.data.useIntegral,
          regularId: that.data.selectRegular.id,
          upPoint: that.data.upPoint.id,
          downPoint:  that.data.downPoint.id,
        };

        app.basePost(app.U({ c: 'auth_api', a:'create_bus_order',q:{key:res.data.key}}),pdata,function(res1){
          var status = res1.data.status,orderId = res1.data.result.orderId, jsConfig = res1.data.result.jsConfig;
          
          switch (status){
          
            case 'SUCCESS':
                wx.hideLoading();
                return app.Tips({ title: '支付成功', icon:'success' }, { tab: 4, url: '/pages/bus_buy_success/bus_buy_success'});        
              break;
            case 'WECHAT_PAY':
              that.setData({toPay:true});
              wx.requestPayment({ 
                timeStamp: jsConfig.timestamp,
                nonceStr: jsConfig.nonceStr,
                package: jsConfig.package,
                signType: jsConfig.signType,
                paySign: jsConfig.paySign,
                success: function (res2) {
                
                  wx.hideLoading();
                  // if (that.data.BargainId || that.data.combinationId || that.data.pinkId || that.data.seckillId) return app.Tips({ title: '支付成功', icon: 'success' }, { tab: 4, url: goPages });
                  return app.Tips({ title: '支付成功', icon:'success' }, { tab: 4, url: '/pages/bus_buy_success/bus_buy_success'});                },
                fail:function(res3){
                  wx.hideLoading();
                  app.basePost(app.U({ c: 'auth_api', a:'user_remove_order',q:{uni:orderId}}),pdata,function(res){
                    return app.Tips({ title: '取消支付' }, {});
                  });
               
                },
                complete:function(res4){
                  wx.hideLoading();
                  //关闭当前页面跳转至订单状态
                  if (res4.errMsg == 'requestPayment:cancel'){ app.basePost(app.U({ c: 'auth_api', a:'user_remove_order',q:{uni:orderId}}),pdata,function(res){
                    return app.Tips({ title: '取消支付' }, {});
                  });
                }
                },
              })
              break;
            case 'PAY_DEFICIENCY':
              wx.hideLoading();
              //余额不足
              return app.Tips({ title: res1.msg},{});
              break;
          }
        },function(res){
          wx.showToast({
            title: res.msg,
            icon: "none"
        });
        });
      },function (res) {
        wx.showToast({
          title: res.msg,
          icon: "none"
      });
      });
     }
    
  },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
  
    },
  
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      if(!app.globalData.userPhone){
        this.setData({
          isLogin: false
        })
  
        }else{
          this.setData({
            isLogin: true
          })
        }
    },
  
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
  
    },
  
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
  
    },
  
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
  
    },
  
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
  
    },
  
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
  
    }
  })